package com.ys.web.user.friends.controller;

import com.ys.base.BaseConstants;
import com.ys.base.EnumType;
import com.ys.utils.annotation.GroupValidateAnnotation;
import com.ys.utils.base.http.McodeHandler;
import com.ys.utils.base.http.ResponseHandler;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.GroupKey;
import com.ys.utils.spring.properties.Config;
import com.ys.web.user.friends.po.BaseGroupInfoPO;
import com.ys.web.user.friends.po.BaseUserFriendsPO;
import com.ys.web.user.friends.service.GroupApplyService;
import com.ys.web.user.friends.service.GroupService;
import com.ys.web.user.friends.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author quxinjun
 * @version 1.0.0
 * @ClassName GroupController.java
 * @Description 组别信息控制器
 * @createTime 2021年05月10日 14:06:00
 */
@Slf4j
@RestController
@RequestMapping("/group")
public class GroupController {


    @Autowired
    private GroupService groupService;

    @Autowired
    private GroupApplyService groupApplyService;

    @PostMapping("/addGroupApply")
    public String addGroupApply(@RequestAttribute Long uid) {
        groupApplyService.addGroupApply(uid);
        return ResponseHandler.success("已发出申请，请等待审核");
    }

    @PostMapping("/getApplyStatus")
    public String getApplyStatus(@RequestAttribute Long uid) {
        return ResponseHandler.success(groupApplyService.getApplyStatus(uid));
    }


    /**
     * @param uid     用户id
     * @param members 成员列表
     * @title addGroup
     * @description 添加群
     * @author quxinjun
     * @updateTime 2021/5/14 15:38
     * @return: java.lang.String
     */
    @PostMapping("/addGroup")
    public String addGroup(@RequestAttribute Long uid, String name, String members) {
        Boolean applyStatus = groupApplyService.getApplyStatus(uid);
        if (!applyStatus) {
            return ResponseHandler.error("500", "创建失败");
        }
        Boolean isOk = Boolean.parseBoolean(Config.pp.getOrDefault(BaseConstants.SwitchConstants.SWITCH_ADD_GROUP, "true"));
        if (!isOk) {
            return ResponseHandler.error("500", "当前功能已关闭，请等待通知");
        }
        if (StringHandler.isEmpty(name)) {
            return ResponseHandler.error("500", "默认群名称不能为空");
        }
        String keyWord = Config.pp.get("msg.data.key.word.list");
        name = StringHandler.keywordReplace(keyWord,name);
        if (StringHandler.isEmpty(members) || members.isEmpty()) {
            return ResponseHandler.error("500", "请选择群成员");
        }
        Long id = groupService.addGroup(uid, name, new HashSet<>(Arrays.stream(members.split(",")).collect(Collectors.toList())));
        return ResponseHandler.success(id);
    }

    /**
     * @param uid     用户id
     * @param groupId 组 id
     * @title delGroup
     * @description 删除群
     * @author quxinjun
     * @updateTime 2021/5/14 15:38
     * @return: java.lang.String
     */
    @PostMapping("/delGroup")
    public String delGroup(@RequestAttribute Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        groupService.delGroup(uid, groupId);
        return ResponseHandler.success();
    }

    /**
     * @param uid      操作人id
     * @param groupId  组id
     * @param memberId 成员id
     * @title turnGroup
     * @description 移交群主
     * @author quxinjun
     * @updateTime 2021/5/14 19:31
     * @return: java.lang.String
     */
    @PostMapping("/turnGroup")
    public String turnGroup(@RequestAttribute Long uid, String groupId, String memberId) {
        Boolean flag = Boolean.parseBoolean(Config.pp.getOrDefault(BaseConstants.SwitchConstants.SWITCH_TURN_GROUP, "false"));
        if (!flag) {
            return ResponseHandler.error("500", "当前功能已关闭");
        }
        if (StringHandler.isEmpty(groupId) || StringHandler.isEmpty(memberId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        groupService.turnGroup(uid, groupId, memberId);
        return ResponseHandler.success();
    }

    /**
     * @param uid      用户id
     * @param memberId 成员id
     * @param groupId  群id
     * @title delMemberByMemberId
     * @description
     * @author quxinjun
     * @updateTime 2021/5/18 11:12
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/delMemberByMemberId")
    public String delMemberByMemberId(@RequestAttribute Long uid, String memberId, String groupId) {
        if (StringHandler.isEmpty(groupId) || StringHandler.isEmpty(memberId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        if (String.valueOf(uid).equals(memberId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "无法删除自己，操作失败");
        }
        groupService.delMemberByMemberId(uid, memberId, groupId);
        //拉黑用户
        List<String> ids = Arrays.asList(memberId.split(","));
        for (String blackUserId:ids ) {
            long blackUid = McodeHandler.from32Radix(blackUserId);
            try {
                if(groupService.groupUserBlackCount(blackUid,groupId)<=0){
                    //添加拉黑信息
                    groupService.groupUserBlack(uid,groupId,blackUid);
                }
            }catch (Exception e){
                log.error("拉黑用户失败，用户id【"+blackUserId+"】",e);
            }

        }
        return ResponseHandler.success();
    }


    /**
     * @param uid     操作人id
     * @param groupId 组id
     * @title getCanInviteList
     * @description 获取当前用户在当前组可邀请的用户信息
     * @author quxinjun
     * @updateTime 2021/5/18 14:24
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/getCanInviteList")
    public String getCanInviteList(@RequestAttribute Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        List<BaseUserFriendsPO> list = groupService.getCanInviteList(uid, groupId);
        return ResponseHandler.list(list);
    }

    /**
     * @param uid     操作人id
     * @param groupId 组id
     * @title getCanDeleteList
     * @description 获取可删除的成员信息
     * @author quxinjun
     * @updateTime 2021/5/25 10:34
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/getCanDeleteList")
    public String getCanDeleteList(@RequestAttribute Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        List<UserGroupVO> list = groupService.getCanDeleteList(uid, groupId);
        return ResponseHandler.list(list);
    }


    /**
     * @param uid     操作用户id
     * @param groupId 组id
     * @title getGroupDetail
     * @description 获取组的信息（人员信息，组的基础信息）
     * @author quxinjun
     * @updateTime 2021/5/18 16:35
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/getGroupDetail")
    public String getUserGroupDetail(@RequestAttribute Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        UserGroupInfoVO userGroupInfoVO = groupService.getGroupDetail(uid, groupId);
        return ResponseHandler.success(userGroupInfoVO);
    }

    /**
     * @param groupId 组id
     * @title getGroupBaseInfo
     * @description 获取组的基本信息
     * @author quxinjun
     * @updateTime 2021/5/25 11:06
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/getGroupBaseInfo")
    public String getGroupBaseInfo(@RequestAttribute Long uid, String groupId, String unValidate) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        BaseGroupInfoPO baseGroupInfoPO = groupService.getGroupBaseInfo(uid, groupId);
        return ResponseHandler.success(baseGroupInfoPO);
    }

    /**
     * @param uid     用户id
     * @param groupId 组id
     * @param type    操作类型
     * @param value   值
     * @title setGroupBase
     * @description 设置基本信息
     * 0.设置群昵称
     * 1.设置群头像
     * 2.设置群名称
     * 3.设置群公告
     * @author quxinjun
     * @updateTime 2021/5/19 10:00
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/setGroupBase")
    public String setGroupBase(@RequestAttribute Long uid, String groupId, Integer type, String value) {
        if (StringHandler.isEmpty(groupId) || StringHandler.isEmpty(type) || StringHandler.isEmpty(value)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        if(type==0 || type==2){
            String keyWord = Config.pp.get("msg.data.key.word.list");
            value = StringHandler.keywordReplace(keyWord,value);
        }
        groupService.setGroupBase(uid, groupId, type, value);
        return ResponseHandler.success();
    }


    /**
     * @param uid      用户id
     * @param groupId  组id
     * @param memberId 成员id
     * @title addGroupMember
     * @description 添加组成员
     * @author quxinjun
     * @updateTime 2021/5/19 11:41
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/addGroupMember")
    public String addGroupMember(@RequestAttribute Long uid, String groupId, String memberId) {
        if (StringHandler.isEmpty(groupId) || StringHandler.isEmpty(memberId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        String key = GroupKey.addMemberKey(groupId);
        if (Redis.str.setNX(key)) {
            groupService.addGroupMember(uid, groupId, memberId);
        } else {
            return ResponseHandler.error("500", "操作冲突，请稍后再试");
        }
        Redis.key.del(key);
        return ResponseHandler.success();
    }

    /**
     * @param uid       用户id
     * @param searchKey 查询关键字
     * @title getGroupList
     * @description 获取用户所有的群信息
     * @author quxinjun
     * @updateTime 2021/5/19 15:07
     * @return: java.lang.String
     */
    @PostMapping("/getGroupList")
    public String getGroupList(@RequestAttribute Long uid, String searchKey) {
        List<BaseGroupInfoPO> list = groupService.getGroupList(uid, searchKey);
        List<BaseGroupInfoPO> collect = list.stream().sorted(Comparator.comparing(BaseGroupInfoPO::getId)).collect(Collectors.toList());
        return ResponseHandler.list(collect);
    }

    /**
     * @param groupId
     * @throws
     * @title getGroupMembersSize
     * @description 获取指定群当前的成员人数
     * @author quxinjun
     * @updateTime 2021/5/21 17:50
     * @return: java.lang.String
     */
    @PostMapping("/getGroupMembersSize")
    public String getGroupMembersSize(String groupId) {
        return ResponseHandler.success(groupService.getGroupMembersSize(groupId));
    }


    /**
     * @param uid      操作人id
     * @param memberId 成员id，逗号隔开
     * @param type     操作类型【1，同意，其他：不同意（默认同意）】
     * @param groupId  组id
     * @title audit
     * @description 审核
     * @author quxinjun
     * @updateTime 2021/5/24 16:04
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/audit")
    public String audit(@RequestAttribute Long uid, String groupId, String memberId, Integer type) {
        if (StringHandler.isEmpty(groupId) || StringHandler.isEmpty(memberId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        if (type == null) {
            type = 1;
        }
        String key = GroupKey.addAuditKey(groupId, memberId);
        if (Redis.str.setNX(key)) {
            groupService.audit(groupId, uid, memberId, type);
        } else {
            return ResponseHandler.error("500", "操作太频繁，请稍后再试");
        }
        Redis.key.del(key);
        return ResponseHandler.success();
    }

    /**
     * @param uid     操作人id
     * @param groupId 组id
     * @title getUnAuditMemberList
     * @description 获取未审核成员列表
     * @author quxinjun
     * @updateTime 2021/5/24 17:41
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/getUnAuditMemberList")
    public String getUnAuditMemberList(@RequestAttribute Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        return ResponseHandler.list(groupService.getUnAuditMemberList(uid, groupId));
    }


    /**
     * @param uid     操作人id
     * @param groupId 组id
     * @title exitGroupByGroupId
     * @description 用户退出群
     * @author quxinjun
     * @updateTime 2021/5/24 18:38
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/exitGroupByGroupId")
    public String exitGroupByGroupId(@RequestAttribute Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        groupService.exitGroupByGroupId(uid, groupId);
        return ResponseHandler.success();
    }


    /**
     * @param groupId 组id
     * @param type    操作类型【0：踢出,2：退出】
     * @title getMemberLeaveList
     * @description 获取退群成员或踢出成员集合
     * @author quxinjun
     * @updateTime 2021/5/24 20:06
     * @return: java.lang.String
     */
    @PostMapping("/getMemberLeaveList")
    public String getMemberLeaveList(String groupId, Integer type, String searchKey) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        if (type == null) {
            type = 0;
        }
        List<UnAuditVO> list = groupService.getMemberLeaveList(groupId, type, searchKey);
        return ResponseHandler.list(list);
    }

    /**
     * @param uid       操作用户id
     * @param groupId   群组id
     * @param searchKey 搜索关键字
     * @title getCurrentGroupMembers
     * @description 获取当前群组成员信息
     * @author quxinjun
     * @updateTime 2021/5/26 11:51
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/getCurrentGroupMembers")
    public String getCurrentGroupMembers(@RequestAttribute Long uid, String groupId, String searchKey) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        List<UserGroupVO> list = groupService.getCurrentGroupMembers(uid, groupId, searchKey);
        return ResponseHandler.list(list);
    }

    /**
     * @param uid      操作人id
     * @param groupId  组id
     * @param inviteId 邀请人id
     * @title joinGroup
     * @description 用户通过群id 加入群聊
     * @author quxinjun
     * @updateTime 2021/5/25 11:54
     * @return: java.lang.String
     */
    @PostMapping("/joinGroup")
    public String joinGroup(@RequestAttribute Long uid, String groupId, String inviteId) {
        if (StringHandler.isEmpty(groupId) || StringHandler.isEmpty(inviteId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        //群用户拉黑开关
        if(StringHandler.getInt(Config.pp.get("group.user.black.isopen"),0)==1) {
            if(StringHandler.getInt(Config.pp.get("group.user.black.type"),0)==0) {
                //用户是否拉黑
                int i = groupService.groupUserBlackCount(uid, groupId);
                if (i > 0) {
                    return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "当前人员不能加人，请联系管理员");
                }
            }else{
                int i = groupService.groupUserByidBlackCount(uid);
                if (i > 0) {
                    return ResponseHandler.success("");
                }
            }
        }
        groupService.joinGroup(uid, groupId, inviteId);
        return ResponseHandler.success("");
    }

    /**
     * @param groupId 组id
     * @title getInactiveList
     * @description 获取指定群不活跃成员集合
     * @author quxinjun
     * @updateTime 2021/5/25 19:18
     * @return: java.lang.String
     */
//    @RedisCache(timeOut = 60 * 60 * 24)
    @GroupValidateAnnotation
    @PostMapping("/getInactiveList")
    public String getInactiveList(@RequestAttribute Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        InactiveVO inactiveVO = groupService.getInactiveList(uid, groupId);
        return ResponseHandler.success(inactiveVO);
    }


    /**
     * @param groupId  群组id
     * @param memberId 成员id
     * @title queryMemberInfo
     * @description
     * @author quxinjun
     * @updateTime 2021/5/28 11:30
     * @return: java.lang.String
     */
    @GroupValidateAnnotation
    @PostMapping("/queryMemberInfo")
    public String queryMemberInfo(@RequestAttribute Long uid, String groupId, String memberId) {
        if (StringHandler.isEmpty(groupId) || StringHandler.isEmpty(memberId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        BaseUserFriendsPO baseUserFriendsPO = groupService.queryMemberInfo(uid, groupId, memberId);
        return ResponseHandler.success(baseUserFriendsPO);
    }

    /**
     * @param uid     操作人id
     * @param groupId 群Id
     * @title getGroupApiInfo
     * @description 获取群助手信息
     * @author quxinjun
     * @updateTime 2021/8/5 12:44
     */
    @PostMapping("/getGroupApiInfo")
    public String getGroupApiInfo(@RequestAttribute("uid") Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId) || StringHandler.isEmpty(uid)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        GroupAssistantVO result = groupService.getGroupApiInfo(uid, groupId);
        return ResponseHandler.success(result);
    }


    /**
     * @param uid     操作人id
     * @param groupId 群id
     * @title resetGroupToken
     * @description 重置群助手身份验证token
     * @author quxinjun
     * @updateTime 2021/8/5 13:01
     * @return: java.lang.String
     */
    @PostMapping("/resetGroupToken")
    public String resetGroupToken(@RequestAttribute("uid") Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId) || StringHandler.isEmpty(uid)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        String token = groupService.resetGroupToken(uid, groupId);
        return ResponseHandler.success(token);
    }


    /**
     * @param uid 操作人id
     * @title getUserAllGroupMembersInfo
     * @description 获取当前用户所有群群成员信息
     * @author quxinjun
     * @updateTime 2021/9/8 13:40
     * @return: java.lang.String
     */
    @PostMapping("/getUserAllGroupMembersInfo")
    public String getUserAllGroupMembersInfo(@RequestAttribute("uid") Long uid) {
        if (StringHandler.isEmpty(uid)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        List<UserGroupVO> list = groupService.getUserAllGroupMembersInfo(uid);
        return ResponseHandler.list(list);
    }


    /**
     * @param id
     * @param memberSize
     * @throws
     * @title addGroupMemberSize
     * @description 修改群成员人数
     * @author quxinjun
     * @updateTime 2022/1/20 3:09
     * @return: java.lang.String
     */
    @PostMapping("/addGroupMemberSize")
    public String addGroupMemberSize(String id, Integer memberSize) {
        if (StringHandler.isEmpty(id)) {
            return ResponseHandler.error("500", "参数传递错误");
        }
        groupService.addGroupMemberSize(id, memberSize);
        return ResponseHandler.success();
    }

    /**
     * @title groupCapacity
     * @description 群扩容
     * @author quxinjun
     * @updateTime 2022/2/23 13:05
     * @return: java.lang.String
     */
    @PostMapping("/groupCapacity")
    public String groupCapacity(@RequestAttribute Long uid, String groupId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error("500", "参数传递错误");
        }
        Integer memberSize = StringHandler.getInt(Config.pp.getOrDefault(BaseConstants.DataSourceConstants.GROUP_CAPACITY_SIZE, "800"));
        groupService.addGroupMemberSize(groupId, memberSize);
        groupService.insertRecord(groupId, uid);
        return ResponseHandler.success();
    }

    /**
     * @author 但何非
     * @dateTime 2023/1/31 21:20
     * @param uid:
     * @param groupId:
     * @return java.lang.String
     * @Description:群用户拉黑接口
     */
    @PostMapping("/group/user/black")
    public String groupUserBlack(@RequestAttribute Long uid,String groupId, @RequestParam(defaultValue = "")String blackUserId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error("500", "参数传递错误");
        }
        if(StringHandler.isEmpty(blackUserId)){
            return ResponseHandler.error("500", "拉黑用户错误");
        }
        long blackUid = McodeHandler.from32Radix(blackUserId);
        if(groupService.groupUserBlackCount(blackUid,groupId)>0){
            return ResponseHandler.error("500", "该用户已拉黑");
        }
        //添加拉黑信息
        groupService.groupUserBlack(uid,groupId,blackUid);

        return ResponseHandler.success();
    }

    /**
     * @author 但何非
     * @dateTime 2023/2/1 11:23
     * @param uid:
     * @param groupId:
     * @return java.lang.String
     * @Description:群用户解除拉黑接口
     */
    @PostMapping("/group/user/black/un")
    public String groupUserBlackUn(@RequestAttribute Long uid,String groupId,@RequestParam(defaultValue = "")String blackUserId) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error("500", "参数传递错误");
        }
        if(StringHandler.isEmpty(blackUserId)){
            return ResponseHandler.error("500", "拉黑用户错误");
        }
        long blackUid = McodeHandler.from32Radix(blackUserId);
        //添加拉黑信息
        groupService.groupUserBlackUn(uid,groupId,blackUid);

        return ResponseHandler.success();
    }

    /**
     * @param groupId 组id
     * @description 群拉黑人员信息
     * @author quxinjun
     * @updateTime 2021/5/24 20:06
     * @return: java.lang.String
     */
    @PostMapping("/group/user/black/list")
    public String groupUserBlackList(@RequestAttribute Long uid,String groupId, String searchKey) {
        if (StringHandler.isEmpty(groupId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递出错");
        }
        List<UnAuditVO> list = groupService.groupUserBlackList(uid,groupId,searchKey);
        return ResponseHandler.list(list);
    }
}
